package services;

import java.util.List;

import com.xyz.User;

import jdbc.ConnectionManager;
import dao.UsersDao;
import errors.AuthentificationException;
import errors.ValidationException;

public class UsersService {
	private UsersService(){}
	
	private static final UsersService instance=new UsersService();
	public static UsersService getInstance(){
		return instance;
	}
	
	private UsersDao usersDao=new UsersDao();
	private ConnectionManager connectionManager=ConnectionManager.getInstance();
	
	public User getUserByLogin(String login){
		try{
			User u=usersDao.getByLogin(login);
			connectionManager.commitTransaction();
			return u;
		}
		catch(Exception e){
			connectionManager.rollbackTransaction();
			throw e;
		}
	}
	
	public User login(String login, String pass) throws AuthentificationException{
		try{
			User u=usersDao.getByLogin(login);
			if (u==null || u.getPass()!=pass)
				throw new AuthentificationException("Wrong login or password");
			connectionManager.commitTransaction();	
			return u;
		}
		catch(Exception e){
			connectionManager.rollbackTransaction();
			throw e;
		}
	}
	
	public List<User> getUsers(int offset, int limit) throws ValidationException{
		
		if (limit<0)
			throw new ValidationException("limit", "limit can't be <0");
		if (offset<0)
			throw new ValidationException("offset", "offset can't be <0");
		
		try{	
			List<User> lu=usersDao.getAll(offset, limit);
			return lu;
		}
		catch(Exception e){
			throw new RuntimeException();
		}
	}
	
	public List<User> getUsersAll(){
		try{	
			List<User> lu=usersDao.getUsersAll();
			return lu;
		}
		catch(Exception e){
			throw new RuntimeException();
		}
	}
	
}
